/* eslint-disable no-console */
/* eslint-disable react/jsx-indent */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Dropdown,
  Menu,
  Divider,
  Popover,
  Modal,
  message,
  Badge,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import { matchDict } from '@/utils/utils';
import styles from '@/utils/utils.less';
import { checkPermissions } from '@/utils/authority';
import TextOverFlow from '@/pages/components/TextOverFlow';
import DictCode from '../../components/DictCode';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ usermanage, loading }) => ({
  usermanage,
  loading: loading.models.usermanage,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
      stateMap: ['', 'default', 'success', 'warning'],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const {
      dispatch,
      location,
      usermanage: {
        pageData: { pagination },
      },
    } = this.props;
    const { isMenuLink } = queryString.parse(location.search);
    dispatch({
      type: 'usermanage/fetchDictList',
      payload: ['COMMON_ENABLED_STATUS', 'USER_TYPE'],
    });
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  }

  searchList = () => {
    this.getList();
  };

  // 获取列表
  getList = (currentPage = 1, pageSize = 10) => {
    const { dispatch, form } = this.props;
    this.setState({
      selectedRowKeys: [],
      selectedRows: [],
    });
    form.validateFields((err, values) => {
      const formFieldsValue = {};
      // 去掉trim
      Object.keys(values).forEach(key => {
        formFieldsValue[key] = values[key] === undefined ? undefined : values[key].trim();
      });
      dispatch({
        type: 'usermanage/updateModalData',
        payload: { formFieldsValue },
      });
      if (!err) {
        dispatch({
          type: 'usermanage/fetchListUserInfo',
          payload: {
            user: formFieldsValue,
            page: {
              currentPage,
              pageSizes: pageSize,
              orderBy: '',
            },
          },
        });
      }
    });
  };

  // 切换表格展开收起
  toggleForm = () => {
    const {
      dispatch,
      usermanage: { expandForm },
    } = this.props;
    dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize);
  };

  // 删除
  delList = userId => {
    const {
      dispatch,
      usermanage: {
        pageData: { pagination },
      },
    } = this.props;
    confirm({
      title: '你确定要删除此条用户吗？',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'usermanage/deleteUserInfo',
          payload: { userId },
          callback: () => {
            message.success('删除成功！');
            this.getList(pagination.current, pagination.pageSize);
          },
        });
      },
      onCancel: () => {},
    });
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        formFieldsValue: {},
      },
    });
    form.resetFields();
  };

  // 重置密码
  reastPasWord = () => {
    const { selectedRowKeys } = this.state;
    const {
      dispatch,
      usermanage: {
        pageData: { pagination },
      },
    } = this.props;
    if (selectedRowKeys.length === 1) {
      confirm({
        title: '你确定要重置密码吗？',
        icon: <ExclamationCircleOutlined />,
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'usermanage/resetUserPwd',
            payload: {
              userIds: selectedRowKeys,
            },
          })
            .then(response => {
              if (response.success) {
                this.getList(pagination.current, pagination.pageSize);
                message.success('重置密码成功！');
              } else {
                message.warning(`${response.message || '重置密码失败！'}`);
              }
            })
            .catch(() => {});
        },
      });
    } else {
      message.warning('只能选择一条数据');
    }
  };

  // 修改启用停用客户状态
  updateStatus = (userId, userStatus) => {
    const {
      dispatch,
      usermanage: {
        pageData: { pagination },
      },
    } = this.props;
    confirm({
      title: `你确定要${userStatus === 2 ? '停用' : '启用'}吗？`,
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'usermanage/enOrdisableUser',
          payload: {
            userId,
            userStatus,
          },
        })
          .then(res => {
            if (res.success) {
              message.success('修改成功！');
              this.getList(pagination.current, pagination.pageSize);
            } else {
              message.warning('状态修改失败！');
            }
          })
          .catch(() => {});
      },
    });
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    await this.resetSearch();
    await this.getList();
    const { dispatch } = this.props;
    // const newTabList = tabList.map(item => ({ ...item }));
    dispatch({
      type: 'usermanage/updateModalData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      usermanage: { formFieldsValue },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="用户登录名" {...this.tableSearchLayout}>
              {getFieldDecorator('loginName', {
                rules: [{ message: '最大不超过100个字符', max: 100 }],
                initialValue: formFieldsValue.loginName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属公司" {...this.tableSearchLayout}>
              {getFieldDecorator('corpName', {
                initialValue: formFieldsValue.corpName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={this.searchList}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      usermanage: { formFieldsValue },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="用户登录名" {...this.tableSearchLayout}>
              {getFieldDecorator('loginName', {
                rules: [{ message: '最大不超过100个字符', max: 100 }],
                initialValue: formFieldsValue.loginName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属公司" {...this.tableSearchLayout}>
              {getFieldDecorator('corpName', {
                initialValue: formFieldsValue.corpName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属机构" {...this.tableSearchLayout}>
              {getFieldDecorator('orgName', {
                initialValue: formFieldsValue.orgName,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="用户状态" {...this.tableSearchLayout}>
              {getFieldDecorator('userStatus', {
                initialValue: formFieldsValue.userStatus,
              })(
                <DictCode
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                  dictType="COMMON_ENABLED_STATUS"
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 16 }}>
                <Button type="primary" onClick={this.searchList}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const {
      usermanage: { expandForm },
    } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const {
      usermanage: { pageData, dictData },
      loading,
    } = this.props;
    const { selectedRows, selectedRowKeys, stateMap } = this.state;
    const columns = [
      {
        title: '姓名',
        dataIndex: 'userName',
        width: 80,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (
          <Popover content={text}>
            <div
              style={{
                width: '80px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                cursor: 'pointer',
              }}
            >
              <span>{text}</span>
            </div>
          </Popover>
        ),
      },
      {
        title: '身份证号',
        dataIndex: 'userIdCard',
        width: 110,
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
      },
      {
        title: '用户登录名',
        dataIndex: 'loginName',
        width: 80,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => (
          <Popover content={text}>
            <div
              style={{
                width: '80px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
                cursor: 'pointer',
              }}
            >
              <span>{text}</span>
            </div>
          </Popover>
        ),
      },
      {
        title: '所属公司',
        dataIndex: 'corpName',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '所属部门',
        dataIndex: 'orgName',
        width: 100,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '服务状态',
        dataIndex: 'userStatus',
        width: 100,
        align: 'center',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: (text, record) => (
          <Badge
            key={record.userStatus}
            status={stateMap[record.userStatus]}
            text={text ? matchDict(dictData.COMMON_ENABLED_STATUS, record.userStatus) : '--'}
          />
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        sorter: (a, b) => new Date(b.createTime) - new Date(a.createTime),
        width: 150,
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onCell: () => ({ style: { textAlign: 'center' } }),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        width: 160,
        render: (text, record) => (
          <span>
            <Authorized authority="mgr:user:updateUserInfo" noMatch={null}>
              <a
                onClick={() =>
                  router.push(
                    `/systemmanage/user/update?userId=${record.userId}&&userType=${record.userType}`
                  )
                }
              >
                修改
              </a>
              <Divider type="vertical" />
            </Authorized>
            <Dropdown
              overlay={
                <Menu>
                  <Menu.Item
                    key="look"
                    onClick={() => router.push(`/systemmanage/user/detail?userId=${record.userId}`)}
                  >
                    查看
                  </Menu.Item>
                  {Number(record.userStatus) === 1 && checkPermissions('mgr:user:deleteUserInfo') && (
                    <Menu.Item key="delete" onClick={() => this.delList(record.userId)}>
                      删除
                    </Menu.Item>
                  )}
                  {Number(record.userStatus) === 1 || Number(record.userStatus) === 3
                    ? checkPermissions('mgr:user:enOrdisableUser') && (
                        <Menu.Item
                          key="able"
                          onClick={() => this.updateStatus(record.userId, record.userStatus)}
                        >
                          启用
                        </Menu.Item>
                      )
                    : checkPermissions('mgr:user:enOrdisableUser') && (
                        <Menu.Item
                          key="able"
                          onClick={() => this.updateStatus(record.userId, record.userStatus)}
                        >
                          停用
                        </Menu.Item>
                      )}
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: '16px' }}>
            <Authorized authority="mgr:user:insertUserInfo" noMatch={null}>
              <Button
                type="primary"
                style={{ marginRight: 8 }}
                onClick={() => router.push('/systemmanage/user/add')}
                icon={<PlusOutlined />}
              >
                新增
              </Button>
            </Authorized>
            <Authorized authority="mgr:user:restUserPwd" noMatch={null}>
              <Button style={{ marginRight: 8 }} onClick={this.reastPasWord}>
                重置密码
              </Button>
            </Authorized>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageData}
            rowKey="userId"
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
